//
//  sockets.swift
//  App
//
//  Created by melvyn on 2018/8/7.
//

import Vapor
import NIOWebSocket

func sockets(server: NIOWebSocketServer) throws {
    
    server.get("api/lives", LiveStream.parameter) { (socket, req) in
        try req.parameters.next(LiveStream.self).whenSuccess({ (stream) in
            
            socket.onError({ (socket, error) in
                print(error)
            })
            
            socket.onBinary({ (socket, data) in
                guard !data.isEmpty, let user = try? req.requireAuthenticated(User.self) else { return }
                
                let envent = Event.init(code: data.first!)
                switch envent {
                case .comment:
                    let jsonData = data.advanced(by: 1)
                    var comment = try! JSONDecoder().decode(Comment.self, from: jsonData)
                    comment.uid = user.id
                    _ = comment.save(on: req).do({_ in
                        socket.send(try! JSONEncoder.init().encode(comment))
                    })
                default: break
                }
            })
            
            socket.onCloseCode({
                print("close code: ", $0)
            })
        })
    }
}


